<template>
  <view class="select-cinema-page">
    <!-- Header Bar -->
    <view class="header-bar">
      <view class="back-icon" @tap="goBack">
        <image src="/static/images/back-arrow-white.png" mode="aspectFit" />
      </view>
      <text class="title ellipsis">{{ movieInfo.name }}</text>
    </view>

    <!-- Movie Info Section -->
    <view class="movie-info-section">
      <image :src="getPoster(movieInfo.poster)" class="poster-image" mode="aspectFill" />
      <view class="details">
        <text class="movie-name">{{ movieInfo.name }}</text>
        <text class="detail-text">类型：{{ movieInfo.type }}</text>
        <text class="detail-text actors">主演：{{ movieInfo.actor }}</text>
        <text class="detail-text">片长：{{ movieInfo.movieLong }}分钟</text>
      </view>
    </view>

    <!-- Date Selector -->
    <view class="date-selector-container">
      <scroll-view class="date-scroll-view" scroll-x :show-scrollbar="false">
        <view
          v-for="(item, index) in showDates"
          :key="index"
          class="date-item"
          :class="{ active: activeDateIndex === index }"
          @tap="selectDate(index)"
        >
          <text>{{ formatDate(item.show_date) }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- Cinema List -->
    <scroll-view scroll-y class="cinema-list-container">
      <view v-if="cinemaList.length > 0">
        <view
          class="cinema-item"
          v-for="(cinema, index) in cinemaList"
          :key="index"
          @tap="goToCinemaDetail(cinema.cinema_id)"
        >
          <view class="cinema-name">{{ cinema.name }}</view>
          <view class="cinema-address">{{ cinema.specified_address }}</view>
          <view class="cinema-tags">
            <!-- You can add dynamic tags here if available from backend -->
            <text class="tag">小吃</text>
            <text class="tag">杜比全景声厅</text>
          </view>
        </view>
      </view>
      <view v-else class="no-cinema">
        <text>今日暂无排片</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      movieId: null,
      movieInfo: {},
      showDates: [], // Array of available dates for the movie
      cinemaList: [], // List of cinemas for the selected date
      activeDateIndex: 0,
    };
  },
  onLoad(options) {
    if (options.movie_id) {
      this.movieId = options.movie_id;
      this.loadMovieInfo();
      this.loadShowDates();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    getPoster(path) {
      if (!path) return '/static/images/placeholder.png';
      if (path.startsWith('http')) return path;
      return 'http://localhost:9090' + path;
    },
    loadMovieInfo() {
      uni.request({
        url: `http://localhost:9090/findOneMovie?id=${this.movieId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 1) {
            this.movieInfo = res.data.movie;
          }
        },
      });
    },
    loadShowDates() {
      uni.request({
        url: `http://localhost:9090/findMovieScheduleInfo?movieId=${this.movieId}`,
        method: 'GET',
        success: (res) => {
          console.log('【调试】获取排片日期接口 (/findMovieScheduleInfo) 返回:', res.data);
          if (res.data.code === 1 && res.data.movieSchedule.length > 0) {
            this.showDates = res.data.movieSchedule;
            // Automatically load cinemas for the first date
            this.loadCinemasForDate(this.showDates[0].show_date);
          } else {
            console.log('【调试】获取到的日期列表为空，或后端返回 code 不为1。');
          }
        },
        fail: (err) => {
          console.error('【调试】获取排片日期接口 (/findMovieScheduleInfo) 请求失败:', err);
          uni.showToast({ title: '网络错误，无法获取排片日期', icon: 'none' });
        }
      });
    },
    loadCinemasForDate(date) {
      console.log(`【调试】开始为日期 [${date}] 获取影院列表...`);
      this.cinemaList = []; // Clear previous list
      uni.request({
        url: `http://localhost:9090/findMovieCinemaScheduleInfo?movieId=${this.movieId}&showDate=${date}`,
        method: 'GET',
        success: (res) => {
          console.log(`【调试】获取影院列表接口 (/findMovieCinemaScheduleInfo) for date [${date}] 返回:`, res.data);
          if (res.data.code === 1) {
            this.cinemaList = res.data.movieCinema;
            if (!this.cinemaList || this.cinemaList.length === 0) {
              console.log('【调试】影院列表为空数组。');
            }
          } else {
            console.log('【调试】获取影院列表失败，或后端返回 code 不为1。');
          }
        },
        fail: (err) => {
          console.error(`【调试】获取影院列表接口 (/findMovieCinemaScheduleInfo) for date [${date}] 请求失败:`, err);
          uni.showToast({ title: '网络错误，无法获取影院列表', icon: 'none' });
        }
      });
    },
    selectDate(index) {
      this.activeDateIndex = index;
      const selectedDate = this.showDates[index].show_date;
      this.loadCinemasForDate(selectedDate);
    },
    formatDate(dateStr) {
        if (!dateStr) return '';
        // Assuming dateStr is 'YYYY-MM-DD'
        const parts = dateStr.split('-');
        if (parts.length === 3) {
            return `${parts[1]}月${parts[2]}日`;
        }
        return dateStr;
    },
    goToCinemaDetail(cinemaId) {
        // Navigate to the cinema detail or schedule page
        uni.navigateTo({
            url: `/pages/cinema-detail/cinema-detail?cinema_id=${cinemaId}&movie_id=${this.movieId}`
        });
    }
  },
};
</script>

<style>
page {
  background-color: #f4f4f4;
}

.select-cinema-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.header-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background-color: #dd2727;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  z-index: 100;
}

.back-icon {
  position: absolute;
  left: 20rpx;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.back-icon image {
  width: 100%;
  height: 100%;
}
.title {
    font-size: 32rpx;
    font-weight: bold;
    width: 60%;
    text-align: center;
}
.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}


.movie-info-section {
  display: flex;
  padding: 30rpx;
  background-color: #fff;
  margin-top: 88rpx; /* Header height */
  border-bottom: 1rpx solid #eee;
}

.poster-image {
  width: 160rpx;
  height: 224rpx;
  border-radius: 8rpx;
  flex-shrink: 0;
}

.details {
  display: flex;
  flex-direction: column;
  margin-left: 30rpx;
  color: #333;
}
.movie-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 15rpx;
}
.detail-text {
  font-size: 26rpx;
  line-height: 1.5;
  color: #666;
}

.date-selector-container {
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.date-scroll-view {
  white-space: nowrap;
  padding: 20rpx;
}

.date-item {
  display: inline-block;
  padding: 15rpx 30rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
}

.date-item.active {
  background-color: #dd2727;
  color: #fff;
  border-color: #dd2727;
}

.cinema-list-container {
  flex: 1;
  background-color: #fff;
}

.cinema-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.cinema-name {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.cinema-address {
  font-size: 26rpx;
  color: #666;
  margin: 10rpx 0;
}

.cinema-tags {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  font-size: 22rpx;
  color: #ffb400;
  border: 1rpx solid #ffb400;
  padding: 4rpx 10rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
  margin-top: 10rpx;
}

.no-cinema {
  text-align: center;
  color: #999;
  padding: 100rpx 0;
}
</style>